<template>
    <div>

                <div class="cards">
                    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">

                           <el-button style="background: #7052ff; color:#fff;" @click="saveRow">新增账号</el-button>
                                <div style="padding: 0 15px;width: 85%;">
                                
                                        <el-table :data="tableData" style="width: 100%; margin-bottom: 20px;margin-top:20px"
                                            row-key="id"  v-loading="loading" default-expand-all>
                                            <el-table-column prop="userAccount" label="账号"  />
                                            <el-table-column prop="nickName" label="用户昵称" align="center"/>
                                            <el-table-column prop="adminType" label="用户类型" align="center">
                                                <template #default="scope">{{ scope.row.adminType == 0 ? '普通用户' : '管理员' }}</template>
                                            </el-table-column>
                                            <el-table-column fixed="right" label="操作" width="180" align="center">
                                                <template #default="scope">
                                                    <el-button style="color: #7052ff ;" link size="small"
                                                        @click.prevent="editRow(scope.$index, scope.row)"> 编辑</el-button>
                                                    
                                                    <el-button style="color: #7052ff ;" link size="small"
                                                        @click.prevent="deleteRow(scope.$index, scope.row.userId)"> 删除</el-button>
                                                </template>
                                            </el-table-column>
                                        </el-table>
                                    </div>

                    </el-tabs>

                </div>
                <div class="cards" style="margin-top:10px;display: flex; justify-content:center">
                    <el-pagination v-model:current-page="current" v-model:page-size="pages.pageSize"
                        :page-sizes="[20, 30, 40, 50]" :size="pages.pageNo" layout="total, sizes, prev, pager, next, jumper"
                        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>



            <el-drawer v-model="drawer" :title="Tips" size="50%" :before-close="handleClose">
                <el-form ref="ruleFormRef" :rules="rules" :model="uttForm" label-width="auto">
                    <p style="margin-bottom:10px;font-size:16px">用户信息</p>
                    <el-form-item label="账号" prop="userAccount">
                            <el-input v-model="uttForm.userAccount" placeholder="请填写" />
                        </el-form-item>
                    <el-form-item label="昵称" prop="nickName">
                        <el-input v-model="uttForm.nickName" placeholder="请填写" />
                    </el-form-item>
                    <el-form-item label="用户类型">
                        <el-select v-model="uttForm.adminType">
                            <el-option :value="0" label="普通用户"></el-option>
                            <el-option :value="1" label="管理员"></el-option>
                        </el-select>
                    </el-form-item>
                     <el-form-item label="密码" v-if="Tips != '编辑账号'" prop="userPassword">
                        <el-input type="password"  v-model="uttForm.userPassword" placeholder="请填写" />
                    </el-form-item>
                    <el-form-item label="修改密码" v-if="Tips == '编辑账号'" prop="userPassword">
                        <el-input  placeholder="请填写" v-model="uttForm.userPassword" type="password"></el-input>
                    </el-form-item>
                    <el-form-item label="再次输入密码" v-if="Tips != '编辑账号'"  prop="respassword">
                        <el-input type="password" v-model="uttForm.respassword" placeholder="请填写" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="CloseAdd()">取消</el-button>
                    <el-button style="background: #7052ff; color:#fff;" @click="handleSaveAdd()">保存</el-button>
                </template>
            </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, onMounted, reactive, computed, ref } from 'vue';
import type { TabsPaneContext } from 'element-plus'
import { ElMessage, ElMessageBox, FormRules, FormInstance } from 'element-plus'
const Card = defineAsyncComponent(() => import('@/components/cards/index.vue'))
import { User, Plus, Warning, QuestionFilled } from '@element-plus/icons-vue';
import { userpage, update,add,del } from '@/api/index'
import router from '@/router';

const drawer = ref(false)
const activeName = ref('first')

const Tips = ref('新增账号')
const current = ref<number>(1)
const total = ref<number>(0)
const ruleFormRef = ref<FormInstance>()

const uttForm = ref({
    id:'',
    orgName:'',
    userAccount: '',
    newPassword: '',
    userPassword: '',
    adminType: 0,
    respassword:''
})




const pages = ref({
    pageNo: 1,
    pageSize: 20,
})
const loading = ref(false)
// 默认选中的值

const GetPage = async () => {
    console.log('-=-=-=',)
    loading.value = true
    const res = await userpage(pages.value)
    console.log('-=-=-ss=', res)
    tableData.value = res.data.records
    total.value = res.data.total
    if (res.code == 200) {
        loading.value = false
    }
}

const getDAta = async () => {
    const res = await getslist()
    sysUserData.value = res.data

}



onMounted(() => {
 GetPage()
})

interface Tree {
    label: string
    children?: Tree[]
}

const propss = {
    label: 'title',
    children: 'children',
    value: 'id',
    // disabled: 'disabled',
}

const data: Tree[] = []
const defaultProps = {
    children: 'children',
    label: 'title',
}



const handleClose = () => {
    drawer.value = false
    ruleFormRef.value?.resetFields()
}

const editRow = async (i: String, row: Object) => {
    Tips.value = '编辑账号'
    drawer.value = true
    uttForm.value = row
    
}

const saveRow = async () => {
    drawer.value = true
    Tips.value = '新增账号'
}


const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    pages.value.pageSize = val
    GetPage()
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    pages.value.pageNo = val
    GetPage()
}

const deleteRow = (i: String, row: any) => {
    console.log('res',row)
    ElMessageBox.confirm(
        '是否确认删除账号?删除后该账号将被删除，无法恢复，历史归属数据仍会保留。',
        '提示',
        {
            confirmButtonText: '确认删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            const res = await del(row)
            if (res.code === 200) {
                GetPage()
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
            }
            
        })
}



const tableData = ref([])

const rules = reactive<FormRules<RuleForm>>({
    userAccount: [{ required: true, message: '请填写', trigger: 'blur' }],
   
    nickName: [
        { required: true, message: '请填写', trigger: 'blur' },
    ],
   
    
    userPassword: [
        { required: true, message: '请填写', trigger: 'blur' },
        { min: 6, max: 16, message: '密码长度应为 6 到 16 个字符', trigger: 'blur' },
    ],
    respassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== uttForm.value.userPassword) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback();
                }
            },
            trigger: 'blur',
        },
    ],
   
})



const handleSaveAdd =  () => {
    ruleFormRef.value?.validate(async (valid:any) => {
        if (valid) {
           uttForm.value.id = Tips.value == '新增账号'?uttForm.value.id : uttForm.value.userId
           const res =  Tips.value == '新增账号' ? await add(uttForm.value) : await update(uttForm.value)
            console.log('打印',res)
            await GetPage()
            drawer.value = false
            ruleFormRef.value?.resetFields()
        } else {
            console.log('error submit!',)
        }
    })
}

const CloseAdd = () => {
    ruleFormRef.value?.resetFields();
    drawer.value = false
}


const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event)
}

</script>

<style scoped lang="scss">
.ache_left {
    min-width: 200px;
    border-right: 1px solid #f7f4f4;
    min-height: 770px;
    padding-right: 20px;
}
</style>